package com.leyou.cart.service;
import com.leyou.cart.entity.Favorite;
import com.leyou.cart.mapper.FavoriteMapper;
import com.leyou.cart.pojo.Cart;
import com.leyou.common.auth.pojo.UserHolder;
import com.leyou.common.constant.LyConstant;
import com.leyou.common.exception.pojo.ExceptionEnum;
import com.leyou.common.exception.pojo.LyException;
import com.leyou.common.utils.BeanHelper;
import com.leyou.common.utils.JsonUtils;
import com.leyou.item.client.ItemClient;
import com.leyou.item.entity.Sku;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class CartService {

    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private FavoriteMapper favoriteMapper;
    @Autowired
    private ItemClient itemClient;

    //练习redis的hash操作
    public void addCart(Cart cart) {
        //获取用户id
        Long userId = UserHolder.getUserId();
        //得到当前用户在redis中的购物车数据的key
        String redisKey = LyConstant.CART_PRE+userId;
        //先得到原来当前用户的购物车列表
        BoundHashOperations<String, String, String> redisHash = redisTemplate.boundHashOps(redisKey);
        //得到当前新添加的购物车对象在redis中的hashKey
        String hashKey = cart.getSkuId().toString();
        //判断新添加的购物车对象是否在其中
        if(redisHash.hasKey(hashKey)){
            //得到redis中原来与新添加的skuid一致的购物车对象
            Cart redisCart = JsonUtils.toBean(redisHash.get(hashKey), Cart.class);
            //如果在，合并数量，此刻新保存的购物车对象，已经包含了原来对应sku购物车对象的数量
            cart.setNum(cart.getNum()+redisCart.getNum());
        }
        //不在，无需操作  直接保存新添加的cart即可
        //再次保存购物车 再次保存，没有hashKey会新加，有会覆盖
        redisHash.put(hashKey, JsonUtils.toString(cart));
    }

    /**
     * 在redis中购物车的数据各式为<redisKey, <hashKey, cartStr>>
     *     现在只要cartStr的集合
     * @return
     */
    public List<Cart> queryCarts() {
        //获取用户id
        Long userId = UserHolder.getUserId();
        //得到当前用户在redis中的购物车数据的key
        String redisKey = LyConstant.CART_PRE+userId;
        //先得到原来当前用户的购物车列表
        BoundHashOperations<String, String, String> redisHash = redisTemplate.boundHashOps(redisKey);
        if(redisHash!=null){
            Map<String, String> entries = redisHash.entries();
            List<Cart> carts = entries.values()//得到所有的cartStr字符串集合
                    .stream()//转流
                    .map(cartStr -> JsonUtils.toBean(cartStr, Cart.class))//将每个字符串格式的购物车对象转成Cart对象
                    .collect(Collectors.toList());
            return carts;
        }
     return null;
    }

    public void addCarts(List<Cart> carts) {
        for (Cart cart : carts) {
            addCart(cart);
        }
    }
    /**
     * 添加收藏
     * @return
     */
    public void addFavorite(String skuid) {
        List<String> stringid = new ArrayList<>();
        stringid.add(skuid);
        List<Long> ids = stringid.stream().map(i -> Long.parseLong(i)).collect(Collectors.toList());
        Long userId = UserHolder.getUserId();
        Favorite record = new Favorite();
        record.setUserId(userId);
        List<Favorite> userCollections = favoriteMapper.select(record);
        if(userCollections!=null){
            List<Long> collect = userCollections.stream().map(Favorite::getSkuId).collect(Collectors.toList());
            if(!Collections.disjoint(collect,ids)){
                throw new LyException(501,"你关注的物品有重复的");
            }
        }
        List<Sku> skus = itemClient.findSkusByIds(ids);
        String redisKey = LyConstant.CART_PRE+userId;
        //先得到原来当前用户的购物车列表
        BoundHashOperations<String, String, String> redisHash = redisTemplate.boundHashOps(redisKey);
        List<Favorite> favoriteList = new ArrayList<>();
        for (Sku sku:skus) {
            Favorite favorite = new Favorite();
            favorite.setSkuId(sku.getId());
            favorite.setImage(sku.getImages());
            favorite.setUserId(userId);
            favorite.setTitle(sku.getTitle());
            favorite.setEnable(sku.getEnable());
            favorite.setOwnSpec(sku.getOwnSpec());
            favorite.setPrice(sku.getPrice());
            favorite.setStock(sku.getStock());
            favoriteList.add(favorite);

        }
        try{
            favoriteMapper.insertList(favoriteList);
            if(redisHash!=null){
                ids.forEach(id->{
                    if(redisHash.hasKey(id.toString())){
                        redisHash.delete(id.toString());
                    }
                });
            }

        }catch (Exception e){
            throw new LyException(ExceptionEnum.INSERT_OPERATION_FAIL);
        }


    }
    /**
     * 删除购物车中的商品并在购物车下方回显
     * @return
     */
    public void deleteCartBySkuId(Long skuId) {
        //获取用户id
        Long userId = UserHolder.getUserId();
        //得到当前用户在redis中的购物车数据的key
        String redisKey = LyConstant.CART_PRE+userId;
        BoundHashOperations<String, String, String> redisHash = redisTemplate.boundHashOps(redisKey);
        String hashKey = skuId.toString();
        if(redisHash.hasKey(hashKey)){
            redisHash.delete(hashKey);
            }



    }

    public boolean deleteCart() {
        //获取用户id
        Long userId = UserHolder.getUserId();
        //得到当前用户在redis中的购物车数据的key
        String redisKey = LyConstant.CART_PRE+userId;
        boolean flag = redisTemplate.delete(redisKey);
        return flag;
    }
    public List<Favorite> queryFavorites() {
        //获取用户id
//        Long userId = UserHolder.getUserId();
        Long userId = 32L;
//        //得到当前用户在redis中的购物车数据的key
//        String redisKey = LyConstant.CART_PRE+userId;
//        //先得到原来当前用户的购物车列表
//        BoundHashOperations<String, String, String> redisHash = redisTemplate.boundHashOps(redisKey);
//        if(redisHash!=null){
//            Map<String, String> entries = redisHash.entries();
//            List<Favorite> favorites = entries.values()//得到所有的cartStr字符串集合
//                    .stream()//转流
//                    .map(favoriteStr -> JsonUtils.toBean(favoriteStr, Favorite.class))//将每个字符串格式的购物车对象转成Cart对象
//                    .collect(Collectors.toList());
//            return favorites;
//        }
//        return null;
        Favorite favorite = new Favorite();
        favorite.setUserId(userId);
        List<Favorite> favoriteList = favoriteMapper.select(favorite);
        if (CollectionUtils.isEmpty(favoriteList)){
            throw  new LyException(501,"用户无收藏");
        }
        return favoriteList;

    }

    public Favorite deleteAndShowFavoriteBySkuId(Long skuId) {
        //获取用户id
        Long userId = UserHolder.getUserId();
        //得到当前用户在redis中的购物车数据的key
        String redisKey = LyConstant.CART_PRE+userId;
        BoundHashOperations<String, String, String> redisHash = redisTemplate.boundHashOps(redisKey);
        String hashKey = skuId.toString();
        if(redisHash.hasKey(hashKey)){
            Favorite favorite = JsonUtils.toBean(redisHash.get(hashKey), Favorite.class);
            try {
                redisHash.delete(hashKey);
            }catch (Exception e){
                throw new LyException(501,"操作失败");
            }
            return favorite;
        }

        return null;
    }

    public void addCartFromFavorite(Long skuId) {
        try {
            Favorite record = new Favorite();
            record.setSkuId(skuId);
            Favorite favorite = favoriteMapper.selectOne(record);
            Cart cart = BeanHelper.copyProperties(favorite, Cart.class);
            cart.setNum(1);
            addCart(cart);
            favoriteMapper.delete(favorite);
        } catch (Exception e) {
            throw new LyException(501,"加入购物车失败");
        }
    }
}
